package com.wechat.pay.api.controller;

import com.wechat.pay.api.service.WxPayService;
import com.wechat.pay.api.vo.Result;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 微信支付
 */
@Slf4j
@RestController
@RequestMapping("wx/pay")
public class WxPayController {
    @Resource
    private WxPayService payService;

    @ApiOperation(value = "统一下单", notes = "统一下单")
    @PostMapping(value = "wxPay")
    public Result wxPay() {
        try {
            return Result.ok(payService.unifiedOrder(null, 0));
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.error();
        }
    }

    @ApiOperation(value = "微信支付回调接口", notes = "微信支付回调接口")
    @PostMapping(value = "wxPayNotify")
    public Result wxPayNotify(HttpServletRequest request) {
        try {
            payService.wxPayNotify(request);
            return Result.ok();
        } catch (Exception e) {
            log.error("wxNotify-error:{}", e.getMessage());
            return Result.error("支付失败");
        }
    }

    @ApiOperation(value = "微信退款", notes = "微信退款")
    @PostMapping(value = "wxRefund")
    public Result wxRefund(@RequestBody Map<String, String> map) {
        try {
            payService.wxRefund(0L, map.get("orderNo"));
            return Result.ok("申请退款成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.error();
        }
    }

    @ApiOperation(value = "微信退款回调", notes = "微信退款回调")
    @PostMapping(value = "wxRefundNotify")
    public Result wxRefundNotify(HttpServletRequest request) {
        try {
            payService.wxRefundNotify(request);
            return Result.ok();
        } catch (Exception e) {
            return Result.error("退款失败");
        }
    }

    @ApiOperation(value = "获取平台证书列表", notes = "获取平台证书列表")
    @PostMapping(value = "getPlatformCertificateList")
    public Result getPlatformCertificateList() {
        try {
            return Result.ok(payService.getPlatformCertificateList());
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            return Result.error();
        }
    }
}